package com.easyExcel.handler;

import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CustomMergeStrategyRow implements RowWriteHandler {
    private int k=0;
    private final List<String> mergeColumnNames;

    private final  Integer dataSize;

    public CustomMergeStrategyRow(List<String> mergeColumnNames, Integer dataSize) {
        this.mergeColumnNames = mergeColumnNames;
        this.dataSize = dataSize;
    }

    private final Map<String, CellRangeAddress> mergedCellMap = new HashMap<>();

    private boolean isCellValueEquals(Cell cell1, Cell cell2) {
        // 比较单元格值
        return cell1.toString().equals(cell2.toString());
    }

    private void mergeRange(Sheet sheet, int firstRow, int lastRow, int cellIndex) {
        CellRangeAddress cellRangeAddress = new CellRangeAddress(firstRow, lastRow, cellIndex, cellIndex);
        sheet.addMergedRegion(cellRangeAddress);
    }

    @Override
    public void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Integer rowIndex, Integer relativeRowIndex, Boolean isHead) {

    }

    @Override
    public void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer relativeRowIndex, Boolean isHead) {

    }

    @Override
    public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer rowIndex1, Boolean isHead) {
        k++;
        Sheet sheet = writeSheetHolder.getSheet();
        int rowIndex = row.getRowNum(); // 当前行的索引（从0开始）
        if(rowIndex<1)
            return;
        String currentCellValue = row.getCell(0).getStringCellValue();



        String prevCellValue = sheet.getRow(rowIndex-1).getCell(0).getStringCellValue();

       Boolean flag=currentCellValue!=null&&currentCellValue.equals(prevCellValue);
//        if (currentCellValue==null || ! currentCellValue.equals(prevCellValue)){
//            return;
//        }
        // 遍历所有需要合并的列名
//        for (String mergeColumnName : mergeColumnNames) {
//            int cellIndex = -1;
            // 找到匹配的列名的索引
            for (int i = 1; i < row.getLastCellNum(); i++) {
                Cell cell = row.getCell(i);
                Row prevRow = sheet.getRow(rowIndex - 1);
//                Cell prevRowCell = prevRow.getCell(0);
//                cellIndex = i;
//                if (cell != null) {
//                    cellIndex = i;
//                    break;
//                }

                // 如果找到匹配的列名，并且上一行有值，则进行合并
//                if (cellIndex != -1) {
                Cell prevCell = (prevRow != null ? prevRow.getCell(i) : null);
                String oldkey = rowIndex-1 + "_" +i;
                String newkey=rowIndex+"_"+i;
                CellRangeAddress existingMergedCell = mergedCellMap.get(oldkey);
                if (existingMergedCell != null) {
                    if (prevCell != null && isCellValueEquals(prevCell, row.getCell(i))&&flag) {
                        mergedCellMap.remove(oldkey);
                        existingMergedCell.setLastRow(rowIndex);
                        if(rowIndex==dataSize){
                            sheet.addMergedRegion(existingMergedCell);
                        }else {
                            mergedCellMap.put(newkey, existingMergedCell);
                        }
                    }else{
                        if(existingMergedCell.getFirstRow()!=existingMergedCell.getLastRow())
                        sheet.addMergedRegion(existingMergedCell);

                        CellRangeAddress newMergedCell = new CellRangeAddress(rowIndex, rowIndex,i, i);
                        mergedCellMap.put(newkey, newMergedCell);
                    }

                } else  if (prevCell != null && isCellValueEquals(prevCell, row.getCell(i))&&flag) {

                    CellRangeAddress newMergedCell = new CellRangeAddress(rowIndex-1, rowIndex,i, i);
                    mergedCellMap.put(newkey, newMergedCell);
                }else if(rowIndex==1) {
                    CellRangeAddress newMergedCell = new CellRangeAddress(rowIndex, rowIndex,i, i);
                    mergedCellMap.put(newkey, newMergedCell);
                }


//                }
            }
        System.out.println("k==============="+k);
    }

}